// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();
// 云函数入口函数
exports.main = async (event, context) => {
  try {
    //首先找到所有的openid
    var openid = new Array();
    var skip = 0;
    while (true) {
      var inquiry = await db.collection('user').skip(skip).get();
      var sizeTemp = inquiry.data.length;
      if (sizeTemp < 100) { //小于100表示所有的数据均已查到
        for (let i = 0; i < sizeTemp; i++) {
          openid.push(inquiry.data[i].openid);
        }
        break;
      } else if (sizeTemp == 100) { //等于100表示有可能还有未查到的数据
        for (let i = 0; i < sizeTemp; i++) {
          openid.push(inquiry.data[i].openid);
        }
        skip += 100;
      }
    }
    //openid 里面存着现在所有用户的id
    const size = openid.length;
    var _log = new Array();
    for (let i = 0; i < size; i++) {
      var tempId = openid[i];
      var count = await db.collection('reviewDays').where({
        user_id: tempId,
      }).count();
      if (count.total == 0) continue;
      var unreviewDays = 0;
      var date = new Date();
      date = new Date(date.getTime() + 8 * 60 * 60 * 1000);
      while (true) {
        date = new Date(date.setTime(date.getTime() - 24 * 60 * 60 * 1000));
        //获取昨天?年份  
        yes_Y = date.getFullYear();
        //获取昨天?月份  
        yes_M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        //获取昨天?日期 
        yes_D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        var yes = await db.collection('reviewDays').where({ //yes：昨天的数据
          user_id: tempId,
          time: {
            year: yes_Y,
            month: yes_M,
            day: yes_D,
          }
        }).get();
        if (yes.data[0] != null) break;
        unreviewDays++;
      }

      if (unreviewDays == 4) {
        var total = await db.collection('message').where({
          user_id: tempId,
        }).count();
        var timeStamp = new Date().getTime();
        await db.collection('message').add({
          data: {
            content: "您好，系统检测到您已经超过三天未完成旧词温习了，时常温习才能记得更牢哦~",
            date: timeStamp,
            message_id: total.total,
            read: false,
            title: "系统通知",
            user_id: tempId,
          }
        })
      }
      var log = tempId + "  unreviewDays: " + unreviewDays;
      _log.push(log);
    }
    return {
      _log: _log,
    }
  } catch (e) {
    console.error(e);
  }

}